package dse.messages.singleversion;

import dse.*;
import dse.messages.*;

import java.util.*;
public class ReadRequestResponseMessageHandler extends MessageSender implements
		MessageHandler {
	private DataObject dobj;
	private LinkedList<Node> nodes;
	private CoordinatorSelector selector;
	private ShareDownloader downloader;
	//private LockProcessor lockProcessor;
	private DataRequest request;
	public ReadRequestResponseMessageHandler(Experiment experiment, DataObject dobj, DataRequest dr, LinkedList<Node> nodes, CoordinatorSelector selector, ShareDownloader downloader, LockProcessor processor){
		super(experiment);
		this.dobj = dobj;
		this.request = dr;
		this.nodes = nodes;
		this.selector = selector;
		this.downloader = downloader;
		//this.lockProcessor = processor;
	}
	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, time);
		if(message.from().isDown())
			this.selector.currentCoordinatorFail(message.from(), recorder, time);
		else{
			this.selector.fail(recorder, time);
		}
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.ReadRequestResponse) {
			recorder.warn(
					"ReadRequestResponseMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}
		Node receiver = message.to();
		receiver.setSequence(Math.max(receiver.getSequence()+1, message.from().getSequence()));
		receiver.sequence();
		if(this.request.getType() == DataRequest.READ){
            int srf = experiment.modules().shareRequestDecisionMaker().sharesToRequestFor(dobj);
            for(int i=0; i<srf; i++){
                Message m = super.createRequestShareV2Message(receiver, nodes.get(i), dobj, nodes.get(i).getDataShare(dobj).getIndex(), downloader);
                recorder.debug(this, "new msg: " + m, time);
                experiment.messageQueue().enqueueMessage(m, time);
            }
        }
        else{
            for(Node n : nodes){
                Message m = super.createMessage(
						MessageType.ShareDataTransfer, receiver, n, dobj, MessagePurpose.DataObjectUpdate,
						new ShareDataTransferMessageHandler (
								experiment,
								dobj,
								n.getDataShare(dobj).getIndex(),
								this.downloader
								)
						);
                recorder.debug(this, "new msg: " + m, time);
                experiment.messageQueue().enqueueMessage(m, time);
            }
		}
	}

}
